package com.haiya.scg.learning.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 局部过滤器
 * @author qiaoguoqiang
 */
@Slf4j
public class UserIdCheckLocalFilter implements GatewayFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getPath().pathWithinApplication().value();
        log.info("请求URL: " + url);
        log.info("method: " + exchange.getRequest().getMethod());

        String username = exchange.getRequest().getQueryParams().getFirst("username");
        String userId = exchange.getRequest().getHeaders().getFirst("user-id");
        log.info("userId: " + userId);

        if (StringUtils.isBlank(userId)) {
            log.info("*****头部验证不通过，请在头部输入 user-id");

            // 终止请求，直接回应
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }
}
